<template>
  <div>
    <a-card title="表格映射区" size="small">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <!-- 数据集 -->
        <a-form-model-item label="数据集" prop="datasetIds">
          <a-select v-model="form.datasetIds" placeholder="请选择数据集" mode="multiple" @change="ondatasetChange">
            <a-select-option :value="item.id" :key="item.id" v-for="item in DsList">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="关联" prop="join" v-show="form.datasetIds && form.datasetIds.length>1">
          <div class="select_group" v-for="(item, index) in form.join" :key="'join'+index">
            <div class="select_item">
              <a-select v-model="item.left.datasetId" @select="onDataLeftChange(index)" >
                <a-select-option :value="data.id" v-for="data in filterData" :key="data.id" :disabled="form.join[index].right.datasetId == data.id">
                  {{data.name}}
                </a-select-option>
              </a-select>
              <span style="padding: 0 5px 0 5px;">的</span>
              <a-select v-model="item.left.column">
                <a-select-option v-for="item in output" :key="item.name" :value="item.name">{{item.displayName}}</a-select-option>
              </a-select>
            </div>
            <span>=</span>
            <div class="select_item">
              <a-select v-model="item.right.datasetId" @select="onDataRightChange(index)" >
                <a-select-option :value="data.id" v-for="data in filterData" :key="data.id" :disabled="form.join[index].left.datasetId == data.id">
                  {{data.name}}
                </a-select-option>
              </a-select>
              <span style="padding: 0 5px 0 5px;">的</span>
              <a-select v-model="item.right.column">
                <a-select-option v-for="item in output" :key="item.name" :value="item.name">{{item.displayName}}</a-select-option>
              </a-select>
            </div>
            <a-icon class="jian_hao" type="minus-circle" v-if="index==form.join.length-1&&index!=0" @click="onReduce(index)" />
          </div>
          <a-button icon="plus" @click="onClick">添加</a-button>

        </a-form-model-item>
        <a-form-model-item label="显示列" prop="columns">
          <a-select mode="multiple" v-model="form.columns">
            <a-select-opt-group v-for="(item,index) in filterData" :key="item.id" :label="item.name">
              <a-select-option v-for="it in filterData[index].output" :key="it.name" :value="item.id + '-' +it.name +'-'+it.displayName">
                {{it.displayName}}
              </a-select-option>
            </a-select-opt-group>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-card>
  </div>
</template>

<script>
  import { mapActions, mapState } from 'vuex'
  export default {
    name: 'Table',
    props:['dataMapping', 'tableForm'],
    data() {
      const ruleJoin = (rule, value, callback) => {
        if (this.form.datasetIds.length > 1) {
          value.forEach(item => {
            if (item.left) {
              if (item.left.datasetId) {} else {callback('关联的数据集不能为空')}
              if (item.left.column) {} else {callback('关联的数据集字段不能为空')}
            }
            if (item.right) {
              if (item.right.datasetId) {} else {callback('关联的数据集不能为空')}
              if (item.right.column) {} else {callback('关联的数据集字段不能为空')}
            }
          })
          callback()
        } else {
          callback()
        }
      }
      return {
        form: {
          datasetIds: [],
          join: [
            {
              left: {},
              right: {}
            }
          ],
          columns: []
        },
        output: [],
        rules: {
          datasetIds: [
            { required: true, message: '数据集不能为空', trigger: 'change' }
          ],
          join: [ {validator: ruleJoin, trigger: 'change'} ],
          columns: [
            { required: true, message: '显示列不能为空', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      ...mapState('custom', ['DsList']),
      filterData () {
        if (!this.form.datasetIds) return []
        const add = this.DsList.filter((v)=>{
          for (let i=0;i<this.form.datasetIds.length; i++) {
            if (this.form.datasetIds[i] == v.id) return v
          }
        })
        if(add.length) {
          return add.map(item=>{
            if (item.type == 0) {
              return {...item, output: JSON.parse(item.output), filter: JSON.parse(item.filter)}
            } else {
              return {...item, output: JSON.parse(item.output), config: JSON.parse(item.config), filter: JSON.parse(item.filter)}
            }
          })
        }else {
          return []
        }
      }
    },
    watch: {
      form : {
        handler (val) {
          for (let key in val) {
            this.dataMapping[key] = val[key]
          }
        },
        deep: true
      }
    },
    methods: {
      ...mapActions('custom', ['getDsList']),
      ondatasetChange (val) {
        if (val.length  <= 1) {
          this.form.join = []
        } else {
          this.form.join = [
            {left: {}, right: {}}
          ]
        }
        this.$set(this.form, 'columns', [])
        this.$set(this.tableForm.display, 'orderBy', '')
      },
      onMapFieldSubmit () {
        let abb = null
        this.$refs.ruleForm.validate(valid => {
          abb = valid
        })
        return abb
      },
      onVerifyForm () {
        const _that = this.form
        if (!_that.datasetIds.length) return false
        if (!_that.columns.length) return false
      },
      onReduce (index) {
        this.form.join.splice(index, 1)
      },
      onDataLeftChange (index) {
        let curId = this.form.join[index].left.datasetId
        const arr = this.DsList.filter((v)=>{
          return v.id==curId
        })
        this.output = JSON.parse(arr[0].output)
      },
      onDataRightChange (index) {
        let curId = this.form.join[index].right.datasetId
        const arr = this.DsList.filter((v)=>{
          return v.id==curId
        })
        this.output = JSON.parse(arr[0].output)
      },
      onClick () {
        this.form.join.push({left: {},right: {}})
      },
      loadDataset () {
        if(JSON.stringify(this.dataMapping) == '{}') {
          this.dataMapping.datasetIds = []
          this.dataMapping.join = [{left: {}, right: {}}]
        }
        this.form = {...this.dataMapping}
      }
    },
    mounted() {
      this.loadDataset()
    },
  }
</script>

<style scoped>
.title {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0,0,0,.85);
  margin-bottom: 15px;
}

.select_item{
  flex: 1;
  display: flex;
}

.select_group {
  display: flex;
  align-items: center;
  position: relative;
}

.jian_hao {
  position: absolute;
  right: -25px;
  top: 8px;
  font-size: 18px;
  cursor: pointer;
}
</style>